<template>
  <el-dialog
    class="add-device"
    title="设备基本信息"
    v-model="state.visible"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    draggable
    @close="() => formRef.resetFields()"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :inline="true"
      label-position="top"
      :rules="formRules"
    >
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          v-model="formModel.companyId"
          :api="selectState.company.api"
          :params="selectState.company.enableParams"
          :valueField="selectState.company.valueField"
          :labelField="selectState.company.labelField"
          :immediate="true"
        />
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          :params="{ companyId: formModel.companyId, enable: 1 }"
          v-model="formModel.areaId"
          :api="selectState.area.api"
          :valueField="selectState.area.valueField"
          :labelField="selectState.area.labelField"
          @change="handleChangeArea"
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="routeId">
        <ApiSelect
          :params="{ areaId: formModel.areaId, enable: 1 }"
          v-model="formModel.routeId"
          :api="selectState.route.api"
          :valueField="selectState.route.valueField"
          :labelField="selectState.route.labelField"
        />
      </el-form-item>

      <el-form-item label="点位名称" prop="positionId">
        <ApiSelect
          @change="positionChange"
          :params="{ routeId: formModel.routeId, enable: 1 }"
          v-model="formModel.positionId"
          :api="selectState.point.api"
          :valueField="selectState.point.valueField"
          :labelField="selectState.point.labelField"
        />
      </el-form-item>

      <el-form-item label="点位类型" prop="positionTypeName">
        <el-input v-model="formModel.positionTypeName" disabled />
      </el-form-item>

      <el-form-item label="设备类型" prop="machineType">
        <el-select
          v-model="formModel.machineType"
          @change="deviceTypeChange"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="设备名称" prop="machineName">
        <el-input v-model.trim="formModel.machineName" maxLength="12" placeholder="设备名称" />
      </el-form-item>

      <el-form-item label="型号" prop="machineModel">
        <el-input
          v-model.trim="formModel.machineModel"
          maxLength="50"
          placeholder="型号"
          disabled
        />
      </el-form-item>

      <el-form-item label="维修负责人" prop="serviceContracts">
        <ApiSelect
          @change="contractChange"
          :params="{
            ...selectState.user.roleParams.repair,
            companyId: formModel.companyId,
            cityName
          }"
          v-model="formModel.serviceContracts"
          :api="selectState.user.api"
          :valueField="selectState.user.valueField"
          :labelField="selectState.user.labelField"
        />
      </el-form-item>

      <el-form-item label="负责人电话" prop="mobile">
        <el-input v-model="formModel.mobile" disabled />
      </el-form-item>

      <el-form-item label="阈值" prop="threshold">
        <el-input-number
          style="width: 210px"
          v-model="formModel.threshold"
          :min="1"
          controls-position="right"
        />
      </el-form-item>

      <el-form-item label="投放地点" prop="positionAddr">
        <MapInput
          v-model:value="formModel.positionAddr"
          v-model:lng="formModel.longitude"
          v-model:lat="formModel.latitude"
        />
      </el-form-item>

      <el-form-item label="设备投放时间" prop="operationTime">
        <el-date-picker
          style="width: 210px"
          v-model="formModel.operationTime"
          type="datetime"
          placeholder="请选择时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="支付方式" prop="payment">
        <el-select v-model="formModel.payment" multiple placeholder="支付方式">
          <el-option
            v-for="item in sys_paytype"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <div style="display: block; width: 50%">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formModel.remark" maxlength="250" show-word-limit type="textarea" />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleAction(false)">取消</el-button>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useOrganApiConfig } from '@/hooks/service'
import { addDevice } from '@/api/device/index'
import { rules } from './rule'

defineExpose({ init })
const emit = defineEmits(['refresh'])
const formRef = ref()
const formRules = ref(rules)
const selectState = useOrganApiConfig()
const { proxy } = getCurrentInstance()
const { device_type, sys_paytype, device_model } = proxy.useDict(
  'device_type',
  'sys_paytype',
  'device_model'
)
console.log(device_model)
const submit = ref(false)
const formModel = reactive({})
const state = reactive({
  visible: false,
  point: null,
  searchValue: '',
  autoCompleteObj: null,
  searchResult: [],
  searchKey: ''
})

function handleAction(confirm) {
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        if (
          !formModel.positionAddr ||
          !formModel.longitude ||
          !formModel.latitude ||
          formModel.latitude === 'undefined' ||
          formModel.positionAddr === 'undefined' ||
          formModel.longitude === 'undefined'
        ) {
          proxy.$modal.msgWarning('使用地图选址获取定位')
          return
        }
        submit.value = true
        formModel.payType = formModel.payment.length > 1 ? 0 : formModel.payment[0]

        addDevice(formModel)
          .then(() => {
            proxy.$modal.msgSuccess('新增成功')
            state.visible = false
            emit('refresh')
            formRef.value.resetFields()
          })
          .finally(() => {
            submit.value = false
          })
      }
    })
  } else {
    formRef.value.resetFields()
    state.visible = false
  }
}

function deviceTypeChange(ev) {
  formModel.machineModel = device_model.value.find((item) => item.value == ev)?.label
}
function positionChange(_, option) {
  formModel.positionTypeName = option?.typeName ?? ''
}
const cityName = ref('')
function handleChangeArea(_, option) {
  let name = option?.name?.split('/')[0]
  cityName.value = name || ''
}
function contractChange(_, option) {
  formModel.mobile = option?.phonenumber ?? ''
}

// 初始化
function init() {
  state.visible = true
}
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  background-color: #fff;
  color: var(--el-color-primary);
}
.add-device .el-input {
  width: 210px;
}
</style>
